﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace ImageProcessing.ParameterForms
{
    public class WindowSizeRankViewModel : INotifyPropertyChanged
    {
        public WindowSizeRankViewModel()
        {
            OkCommand = new DelegateCommand(OkExecute, CanOkExecute);
            CancelСommand = new DelegateCommand(CancelExecute);
            WindowSize = "3";
            Rank = "3";
        }

        #region Commands
        public DelegateCommand OkCommand { get; set; }
        public DelegateCommand CancelСommand { get; set; }
        private bool CanOkExecute(object sender)
        {
            int windowSize;
            int rank;
            int.TryParse(_windowSize, out windowSize);
            int.TryParse(_rank, out rank);
            return (windowSize > 0 && rank > 0) && (rank <= windowSize*windowSize) && (windowSize%2==1);
        }
        private void OkExecute(object sender)
        {
            var handler = OkEventHandler;
            if (handler != null)
                handler(this, new RankWindowSizeEventArgs(int.Parse(Rank), int.Parse(WindowSize)));
        }
        private void CancelExecute(object sender)
        {
            var handler = CancelEventHandler;
            if (handler != null)
                handler(this, new EventArgs());

        }
        #endregion Commands
        public EventHandler CancelEventHandler { get; set; }
        public EventHandler<RankWindowSizeEventArgs> OkEventHandler { get; set; }
        
        
        private string _windowSize;
        public string WindowSize
        {
            get { return _windowSize; }
            set
            {
                _windowSize = value;
                OnPropertyChanged("WindowSize");
                OkCommand.RaiseCanExecuteChanged();
            }
        }
        
        private string _rank;
        public string Rank
        {
            get { return _rank; }
            set
            {
                _rank = value;
                OnPropertyChanged("Rank");
                OkCommand.RaiseCanExecuteChanged();
            }
        }


        #region INotifyPropertyChanged parts
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

    public class RankWindowSizeEventArgs : EventArgs
    {
        public RankWindowSizeEventArgs(int rank, int windowSize)
        {
            Rank = rank;
            WindowSize = windowSize;
        }
        public int Rank { get; set; }
        public int WindowSize { get; set; }
    }
}
